package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Order;
import domain.OrderItem;
import domain.Product;
import domain.User;
import service.OrderService;
import service.ProductService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class CommitOrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            JSONObject object = GetRequestJsonUtils.getRequestJsonObject(req);
            JSONArray cart = object.getJSONArray("cart");
            JSONObject receiver = object.getJSONObject("receiver");
            ProductService productService = new ProductService();
            HttpSession session=req.getSession();
            User user=(User) session.getAttribute("user");

            Order order=new Order();
            order.setId(UUID.randomUUID().toString());
            double total = 0;
            List<OrderItem> items=new ArrayList<>();
            for (int i = 0; i < cart.size(); i++) {
                OrderItem item=new OrderItem();
                item.setOrder(order);
                JSONObject book = (JSONObject) cart.get(i);
                int number = book.getIntValue("number");
                String name = book.getString("name");
                String id = book.getString("id");
                double lineTotal = book.getDoubleValue("lineTotal");
                total += lineTotal;
                Product product = productService.findProductById(id);
                item.setP(product);
                item.setBuynum(number);
                items.add(item);
                if (product.getPnum() < number) {
                    Response build = Response.build(ResponseCode.ERROR, name + "库存不够，请减少购买数量！");
                    resp.setContentType("application/json;charset=utf-8");
                    resp.getWriter().write(JSON.toJSON(build).toString());
                    return;
                }
            }
            String receiverName = null, receiverPhone = null, receiverAddress = null;
            receiverName = receiver.getString("name");
            receiverPhone = receiver.getString("phone");
            receiverAddress = receiver.getString("address");

            order.setMoney(total);
            order.setReceiverAddress(receiverAddress);
            order.setReceiverName(receiverName);
            order.setReceiverPhone(receiverPhone);
            order.setPaystate(0);
            order.setUser(user);
            order.setOrderItems(items);

            OrderService orderService=new OrderService();
            orderService.commitOrder(order);

            Response build = Response.build(ResponseCode.SUCCESS);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());

        }catch (Exception e){
            Response build = Response.build(ResponseCode.ERROR,"请求参数格式不对或数据库异常");
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
        }
    }
}
